package pl.iachoo.ctl.tabory.dao.hibernate.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;

import pl.iachoo.ctl.tabory.dao.api.services.IUserRoleService;
import pl.iachoo.ctl.tabory.dao.data.vo.UserRoleVO;
import pl.iachoo.ctl.tabory.dao.hibernate.services.BaseDaoService;

public class UserRoleDaoServiceImpl extends BaseDaoService<UserRoleVO>
		implements IUserRoleService {

	private final Logger logger = Logger
			.getLogger(UserRoleDaoServiceImpl.class);

	public UserRoleDaoServiceImpl(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserRoleVO> getAllUserRoles() throws Exception {
		logger.debug("Getting all UserRoles");
		Transaction transaction = null;
		Session session = null;
		List<UserRoleVO> list = new ArrayList<UserRoleVO>();
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			transaction.begin();
			Criteria criteria = session.createCriteria(UserRoleVO.class);
			list = criteria.list();
			logger.debug(list);
			transaction.commit();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			transaction.rollback();
			throw e;
		} finally {
			session.close();
		}
		return list;
	}

	@Override
	public UserRoleVO getUserRole(Long userRoleId) throws Exception {
		logger.debug("Getting UserRole for id: " + userRoleId);
		Transaction transaction = null;
		Session session = null;
		UserRoleVO userRole = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			transaction.begin();
			Criteria criteria = session.createCriteria(UserRoleVO.class);
			criteria.add(Restrictions.eq("id", userRoleId));
			userRole = (UserRoleVO) criteria.uniqueResult();
			transaction.commit();
			logger.debug(userRole);
		} catch (Exception e) {
			transaction.rollback();
			logger.error(e.getMessage(), e);
			throw e;
		} finally {
			session.close();
		}
		return userRole;
	}

}
